package count_sub_islands

func countSubIslands(grid1 [][]int, grid2 [][]int) (res int) {
	m, n := len(grid2), len(grid2[0])
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if 1 == grid2[i][j] {
				if dfs(grid1, grid2, i, j) {
					res++
				}
			}
		}
	}
	return
}

func dfs(grid1 [][]int, grid2 [][]int, i, j int) bool {
	m, n := len(grid2), len(grid2[0])
	if i < 0 || i == m || j < 0 || j == n || grid2[i][j] == 0 {
		return true
	}
	grid2[i][j] = 0
	a := dfs(grid1, grid2, i+1, j)
	b := dfs(grid1, grid2, i-1, j)
	c := dfs(grid1, grid2, i, j+1)
	d := dfs(grid1, grid2, i, j-1)
	return a && b && c && d && grid1[i][j] == 1
}
